package com.bw.heishou.Fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bw.heishou.Adapter.MyViewPageAdapter;
import com.bw.heishou.Bean.ResultInfo;
import com.bw.heishou.R;
import com.bw.heishou.Utilise.ImageLoading;
import com.bw.heishou.Utilise.SharedPreferencesUtilise;
import com.bw.heishou.Utilise.Utilise;
import com.bw.heishou.View.MainActivity;
import com.bw.heishou.mvp.view.LogActivity;
import com.bw.heishou.pay.AuthResult;
import com.bw.heishou.pay.PayResult;
import com.bw.heishou.pay.util.OrderInfoUtil2_0;
import com.bw.lib_core.mvp.view.BaseFragent;
import com.flyco.tablayout.SlidingTabLayout;
import com.frame.lib_common.slidingmenu.SlidingMenu;
import com.google.gson.Gson;
import com.wildma.pictureselector.PictureSelector;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.security.auth.login.LoginException;

//支付宝账号密码
//gprdpv4690@sandbox.com
//111111
public class MyFragment1 extends BaseFragent {
    private SlidingTabLayout tabLayout;
    private ViewPager page;
    private TextView fragment1Log;
    SlidingMenu slidingMenu;
    static View menu;
    private String check_money;
    private int paymoney;
    private static final String TAG = "MyFragment1";
    public static Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==100){
                ImageView viewById = menu.findViewById(R.id.sliding_img);
                ImageLoading.getInstance().LoadImaUriCirCle((Uri) msg.obj,viewById);
            }
        }
    };
    @Override
    public int bandlayout() {
        return R.layout.fragment1;
    }

    @Override
    public void initView() {
        initSlidingMenu();
        tabLayout = (SlidingTabLayout) findViewById(R.id.fragment1_tablayout);
        page = (ViewPager) findViewById(R.id.fragment1_page);
        fragment1Log = (TextView) findViewById(R.id.fragment1_log);

        ArrayList<String> title = new ArrayList<>();
        title.add("关注");
        title.add("推介");
        title.add("附近");
        List<Fragment> list = new ArrayList<>();
        list.add(new MyFragment11());
        list.add(new MyFragment12());
        list.add(new MyFragment13());
        page.setAdapter(new MyViewPageAdapter(getActivity().getSupportFragmentManager(),
                FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, list));
        tabLayout.setViewPager(page, title.toArray(new String[title.size()]));
        fragment1Log.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                SharedPreferencesUtilise instance = SharedPreferencesUtilise.getInstance();
                SharedPreferences sharedPreferences = SharedPreferencesUtilise.getInstance().getSharedPreferences();
                boolean islog = sharedPreferences.getBoolean("islog", false);
                if (islog){
                    ToastUtils.showShort("登录");
                    boolean isinitSliding = sharedPreferences.getBoolean("isinitSliding", false);
                    if (!isinitSliding){
                        SharedPreferencesUtilise.getInstance().put("isinitSliding",true);
                        initSlidingMenu();
                    }
                    slidingMenu.showMenu();
                }else {
                    ToastUtils.showShort("未登录");
//                    startActivity(new Intent(getActivity(), LogActivity.class));
                }
            }
        });
    }

    void initSlidingMenu(){
        slidingMenu=new SlidingMenu(getActivity());
        slidingMenu.setMode(SlidingMenu.LEFT);
        slidingMenu.setMenu(R.layout.sliding_item);


        WindowManager manager= (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        int width = manager.getDefaultDisplay().getWidth();
        slidingMenu.setBehindWidth(width/4*3);
        slidingMenu.attachToActivity(getActivity(),SlidingMenu.SLIDING_CONTENT);
        menu = slidingMenu.getMenu();
        ImageView viewById = menu.findViewById(R.id.sliding_img);
        TextView money = menu.findViewById(R.id.sliding_money);
        ImageLoading.getInstance().LoadImaDraCirCle(R.drawable.a3,viewById);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(getActivity(),PictureSelector.SELECT_REQUEST_CODE).selectPicture(true);
            }
        });
        //充值快手币操作
        money.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                AlertDialog.Builder builder= new AlertDialog.Builder(getActivity());
//                builder.setIcon(R.drawable.ic_launcher_background);
//                builder.setTitle("请选择 充值 金额");
//                String[] check=new String[]{"1","10","50","100","500"};
//                builder.setSingleChoiceItems(check, 0, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        ToastUtils.showShort("选中了"+check[which]);
//                    }
//                });
//                //点击确定
//                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        ToastUtils.showShort("确定选中了"+which);
//                        //调用支付宝支付，
////                        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
////                        payV2();
//                    }
//                });
//                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        ToastUtils.showShort("取消选中了"+which);
//                    }
//                });
//                AlertDialog dialog = builder.create();
//                dialog.show();
                AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
                View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.alertitem, null);

                builder.setIcon(R.drawable.ic_launcher_background);
                builder.setTitle("请选择 充值 金额");
                builder.setView(inflate);
                AlertDialog dialog = builder.create();
                dialog.show();
                RadioGroup radioGroup = inflate.findViewById(R.id.alert_rg);

                inflate.findViewById(R.id.alert_queding).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
                        switch (checkedRadioButtonId){
                            case R.id.alert_rg1:
                                check_money= Utilise.CHECK_1;
                                break;
                            case R.id.alert_rg2:
                                check_money= Utilise.CHECK_2;
                                break;
                            case R.id.alert_rg3:
                                check_money= Utilise.CHECK_3;
                                break;
                            case R.id.alert_rg4:
                                check_money= Utilise.CHECK_4;
                                break;
                        }
                        ToastUtils.showShort(check_money);
                        if (check_money.equals("CHECK1")){
                            paymoney=1;
                        }else if (check_money.equals("CHECK2")){
                            paymoney=10;
                        }else if (check_money.equals("CHECK3")){
                            paymoney=50;
                        }else if (check_money.equals("CHECK4")){
                            paymoney=100;
                        }
                        dialog.dismiss();
                        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
                        payV2(paymoney);
                    }
                });
                inflate.findViewById(R.id.alert_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ToastUtils.showShort("取消");
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    @Override
    public void initData() {

    }


    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID = "2021000117666933";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "";

    /**
     *  pkcs8 格式的商户私钥。
     *
     * 	如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 	使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * 	RSA2_PRIVATE。
     *
     * 	建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 	工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQCFU1L5Jdh2YZa9Cu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ZU4Xs4yYKR8ho+C9dhSIUPnpCnZb/MQ1myloy70vJ2JtV/X4oUwaJ6eBJwAtqKDJ/qwFm7o8pQCf9zzCtv9r/To8Aon9Ml9Fa9xZjTrI1xuvdFSn1tDQXMow49cD3ry4XXfwM98D5wKBgD22ir/CET12l+ya0GO1FCpI0Fgc8scWS1ht1b2p4aE3KnJYmBBmbDuHaGj989kGzmMeOnQyJaQhVmLociPfkVkoFPz6wXLPCrYRbp2u4HGE73w39fnSbtI1fCwBono5YEekgIr2wj9iHiUzOoWDRTCITD6O7VDbp68SMHTCmRAtAoGBAN71/mXkmubvG5hjd74SSa3n0tzFJvWwCq0X8lkLnDqL+c5BW87q2dCJcXuSk5OJwTOE6n0KILbq/vHtaKfkV4QBdOzS8AQCDIY26zxauR4+fAhtMeBXjc4bjoHv6/6WRuCUZysBxYbOe7LEkEr1jmsN6SrYAGBRZlyPcAd31ccf";
    public static final String RSA_PRIVATE = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhVNS+SXYdmGWvQroWPdpV0YQk1UIi6GnDdh9V8myDgO6VbLVhqZ+bV1MchwUlHzB2x5phuouFjJteddfqrEgHQE2uXWS/JxkMyewMI1zeiKtG2zwbKwfFqwGNjkZ1lheTUzucHixbcelmdry5t+/wySnVBFbehIhTohLtVb5Hz1An3yt8Mi+fdY57/iSrTbiATgJOl0AnIXI4+PM70HF+bn6aXIW8Hepz4RLEerzhW045rfUzVe/FNEsOp7xsfZ5vfWZbf/mjAKwIZ56WklFfi/ZsCIVk6kxaZWeow6ubUWKZBMO9looo8KgOdhFH9fxB0N831jz4/eBgHK6AG/NAwIDAQAB";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Gson gson=new Gson();
                        Log.i(TAG+"111", ""+resultInfo);
                        ResultInfo resultInfo1 = gson.fromJson(resultInfo, ResultInfo.class);
                        String total_amount=resultInfo1.getAlipay_trade_app_pay_response().getTotal_amount();
                        Log.i(TAG+"111", ""+total_amount);

                        double v = Double.parseDouble(total_amount);

                        ToastUtils.showShort("充值到账:"+v+"元");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtils.showShort("充值失败");
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };


    /**
     * 支付宝支付业务示例
     */
    public void payV2(int mon) {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2,mon);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

}
